<template>
    <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div style="margin-top:15px">
        <el-button
          style="float: right"
          @click="handleSetTimeList()"
          type="primary"
          size="small">
          Set online time in batches
        </el-button>
        <el-button
          style="float:right; margin-right: 15px"
          type="primary"
          @click="handleSearchList()"
          size="small">
          Search
        </el-button>
        <el-upload style="float:right;margin-right: 5px" :on-change="(file, fileList) => {uploadFromFile(file, fileList) }" action="alert"
                :show-file-list="false" :auto-upload="false">
        <el-button
          @click="handleBatchAdd()"
          type="primary"
          icon="el-icon-edit"
          size="small">
          批量添加
        </el-button>
        </el-upload>
      </div>
      <div style="margin-top: 15px;max-width:75%;">
        <el-form :inline="true" :model="listQuery" size="small" label-width="120px">
          <el-form-item label="ModelNickname:" label-width="120px">
            <el-input style="width: 203px" v-model="listQuery.nickName" placeholder="Please enter"></el-input>
          </el-form-item>
          <el-form-item label="ID:" label-width="120px">
            <el-input style="width: 203px" v-model="listQuery.userCode" placeholder="Please enter"></el-input>
          </el-form-item>
          <el-form-item label="Assign Chatter:" label-width="120px">
            <el-select style="width: 203px" v-model="listQuery.hasChatterMode" placeholder="Please enter" clearable>
              <el-option
                v-for="item in verifyStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="CID:" label-width="120px">
            <el-input style="width: 203px" v-model="listQuery.chatterUserCode" placeholder="Please enter"></el-input>
          </el-form-item>
          <el-form-item label="ChatterNickname:" label-width="120px">
            <el-input style="width: 203px" v-model="listQuery.chatterNickName" placeholder="Please enter"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
      <div class="table-container">
        <el-table ref="returnReasonTable"
                  :data="list"
                  style="width: 100%;"
                  @selection-change="handleSelectionChange"
                  v-loading="listLoading" border>
          <el-table-column type="selection" width="60" align="center"></el-table-column>
          <el-table-column label="ID" width="180" align="center">
            <template slot-scope="scope">{{scope.row.userCode}}</template>
          </el-table-column>
          <el-table-column label="Nickname" width="140" align="center">
            <template slot-scope="scope">{{scope.row.nickName}}</template>
          </el-table-column>
          <el-table-column label="Avatar" width="120" align="center">
              <img slot-scope="scope" class="image" :src="scope.row.avatarUrl" />
          </el-table-column>
          <el-table-column label="Gender" align="center">
            <span slot-scope="scope">{{scope.row.gender === 0?"unknown":scope.row.gender==1?"male":"female"}}</span>
          </el-table-column>
          <el-table-column label="Tun-ons" width="380" align="center">
            <template slot-scope="scope">
            <span v-for="(item, index) in scope.row.turnOnDtos" :key="index">
               {{item.turnOns}}{{index!==(scope.row.turnOnDtos.length-1)?',':''}}
            </span>
          </template>
          </el-table-column>
          <el-table-column label="Assign Chatter" width="280" align="center">
            <template slot-scope="scope">{{scope.row.chatterInfo===null||scope.row.chatterInfo===undefined?'':scope.row.chatterInfo.chatterAccount }}({{scope.row.chatterInfo===null||scope.row.chatterInfo===undefined?'undistributed':scope.row.chatterInfo.chatterName}})</template>
          </el-table-column>
          <el-table-column label="Online Time" width="140" align="center">
            <template slot-scope="scope">{{scope.row.onlineTimeStart}}{{scope.row.onlineTimeStart===null||scope.row.onlineTimeStart===undefined?'':'-'}}{{scope.row.onlineTimeEnd}}</template>
          </el-table-column>
          <el-table-column label="Modification Time" width="180" align="center">
            <template slot-scope="scope">{{scope.row.gmtModified}}</template>
          </el-table-column>
          <el-table-column label="Creation Time" width="180" align="center">
            <template slot-scope="scope">{{scope.row.gmtCreate}}</template>
          </el-table-column>
          <el-table-column label="Controls" width="320px" align="center">
            <template slot-scope="scope">
              <a
                class="operation_item"
                @click="handleUpdate(scope.$index, scope.row,0)">Detail</a>
                <a
                style="margin-left:10px; margin-right:10px;"
                class="operation_item"
                @click="handleUpdate(scope.$index, scope.row,1)">Modify online time</a>
              <a
               class="operation_item"
                @click="handleDelete(scope.$index, scope.row)">Delete Account</a>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="batch-operate-container">
      </div>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes,prev, pager, next,jumper"
          :current-page.sync="listQuery.pageNum"
          :page-size="listQuery.pageSize"
          :page-sizes="[10]"
          :total="total">
        </el-pagination>
      </div>
      <el-dialog
        title="Choose online time"
        :visible.sync="dateDialogVisible"  width="50%">
        <el-time-picker
        v-model="startTime"
        type="datetime"
        format="HH:mm"
        placeholder="Start Time">
        </el-time-picker>
        <el-time-picker
        v-model="endTime"
        type="datetime"
        format="HH:mm"
        placeholder="End Time">
        </el-time-picker>
        <span slot="footer" class="dialog-footer">
        <el-button @click="dateDialogVisible = false" size="small">Cancel</el-button>
        <el-button type="primary" @click="setTimeConfirm()" size="small">Confirm</el-button>
      </span>
      </el-dialog>
    </div>
  </template>
  <script>
    import {formatDate} from '@/utils/date';
    import {fetchList,deleteReason,updateStatus,addReason,getReasonDetail,updateReason} from '@/api/returnReason';
    import {fetchModelList,fetchModelOnline,fetchModelDelete,fetchBatchModelUpload} from '@/api/model';
    const defaultListQuery = {
      pageNum: 1,
      pageSize: 10,
      nickName:null,
      hasChatterMode:null,
      userCode:null,
      chatterUserCode:null,
      chatterNickName:null
    };
    const defaultReturnReason = {
      name:null,
      sort:0,
      status:1,
      createTime:null
    };
    export default {
      name: 'returnReasonList',
      data() {
        return {
          list: null,
          total: null,
          multipleSelection: [],
          listLoading:true,
          dateDialogVisible:false,
          listQuery:Object.assign({}, defaultListQuery),
          operateType:null,
          operateOptions: [
            {
              label: "删除",
              value: 1
            }
          ],
          dialogVisible:false,
          startTime:"",
          endTime:"",
          returnReason:Object.assign({},defaultReturnReason),
          operateReasonId:null,
          verifyStatusOptions: [{
          value: "1",
          label: 'yes'
        }, {
          value: "0",
          label: 'no'
        }],
        multipleSelection:[],
        isBatchSettings:false,
        currentRow:null
        }
      },
      created(){
        this.getList();
      },
      filters:{
      },
      methods: {
        centerDialogVisible(){
          this.dialogVisible=false;
          console.log(this.selectTime)
        },
        uploadFromFile(file, fileList) {
          if(this.beforeFileUpload(file)){
          const formData = new FormData();
        formData.append('file', fileList[0].raw);
        this.listLoading = true;
        fetchBatchModelUpload(formData).then(response => {
          this.listLoading = false;
          this.getList();
          this.$message({
                message: 'Successfully uploaded, please wait for 1-5 minutes to refresh',
                type: 'success',
                duration:1000
              });
        });
         }
        },
        beforeFileUpload(file) {
          // var fileExt = file.name.replace(/.+\./,"").toLowerCase(); 
          // const isZIP = ["zip"].indexOf(fileExt) !== -1
          // if (!isZIP) {
          //   this.$message.error('Uploading file can only be in ZIP format!');
          //   return false;
          // }else {
          //   return true;
          // }
          return true;
        },
        formatCreateTime(time) {
          if (time!==null){
            let date;
            let str = ""+time;
            if(str.indexOf("GMT") != -1 ){
             date = new Date(time);
            }else{
              date = new Date(parseInt(str));
            }
            return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
          }

        },
        formatTime(time) {
          if (time!==null){
            let date;
            let str = ""+time;
            if(str.indexOf("GMT") != -1 ){
             date = new Date(time);
            }else{
              date = new Date(parseInt(str));
            }
            return formatDate(date, 'hh:mm')
          }

        },
        handleSetTimeList(){
          this.isBatchSettings = true;
          if(this.multipleSelection==null||this.multipleSelection.length<1){
            this.$message({
              message: 'Please select the entry to operate on',
              type: 'warning',
              duration: 1000
            });
            return;
          }else{
            this.dateDialogVisible = true;
          }
        },
        setTimeConfirm(){
          if(this.startTime !=="" && this.endTime !=="" && this.startTime !==null && this.endTime !==null){
            const startDate = new Date(this.startTime);
            const endDate = new Date(this.endTime);
          if((endDate.getTime()-startDate.getTime())<=0){
            this.$message({
                message: 'The end time must be greater than the start time',
                type: 'warning',
                duration:1000
              });
          }else{
          var modeCodeList = [];
          if(this.isBatchSettings){
           for(let i=0;i<this.multipleSelection.length;i++){
              modeCodeList.push(this.multipleSelection[i].userCode);
           }
          }else{
            modeCodeList.push(this.currentRow.userCode);
          }
          var params = {
            "modeUserCodeList":modeCodeList,
            "onlineTimeStart":this.formatTime(this.startTime),
            "onlineTimeEnd":this.formatTime(this.endTime)
          }
          fetchModelOnline(params).then(response=>{
            this.startTime = "";
            this.endTime = "";
            this.getList();
            this.dateDialogVisible=false;
            this.$message({
                message: 'Successfully set',
                type: 'success',
                duration:1000
              });
              this.getList();
          });
        }
          }else{
            this.$message({
                message: 'Please select a start and end time',
                type: 'warning',
                duration:1000
              });
          }
        },
        handleBatchAdd(){

        },
        handleSearchList(){
          this.listQuery.pageNum = 1;
          this.getList();
        },
        handleAdd() {
          this.dialogVisible=true;
          this.operateReasonId=null;
          this.returnReason=Object.assign({},defaultReturnReason);
        },
        handleConfirm(){
          if(this.operateReasonId==null){
            //添加操作
            addReason(this.returnReason).then(response=>{
              this.dialogVisible=false;
              this.operateReasonId=null;
              this.$message({
                message: '添加成功',
                type: 'success',
                duration:1000
              });
              this.getList();
            });
          }else{
            //编辑操作
            updateReason(this.operateReasonId,this.returnReason).then(response=>{
              this.dialogVisible=false;
              this.operateReasonId=null;
              this.$message({
                message: '修改成功！',
                type: 'success',
                duration:1000
              });
              this.getList();
            });
          }
        },
        handleUpdate(index, row,position){
          this.currentRow = row;
          if(position == 0){
          this.$router.push({path: '/modelDetail', query: {modelUserCode: row.userCode}})
          }else{
            this.isBatchSettings = false;
            this.dateDialogVisible = true;
          }
        },
        handleDelete(index, row){
          this.$confirm('Do you want to delete the Model account?', 'Prompt', {
            confirmButtonText: 'Confirm',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }).then(() => {
            let params = {
              "modeUserCode":row.userCode
            }
            fetchModelDelete(params).then(response=>{
              this.$message({
                message: 'Deleted！',
                type: 'success',
                duration: 1000
              });
              this.listQuery.pageNum=1;
              this.getList();
            });
          })
        },
        handleSelectionChange(val){
          this.multipleSelection = val;
        },
        handleStatusChange(index,row){
          let ids=[];
          ids.push(row.id);
          let param = new URLSearchParams();
          param.append("status",row.status);
          param.append("ids",ids);
          updateStatus(param).then(response=>{
            this.$message({
              message: '状态修改成功',
              type: 'success'
            });
          });
        },
        handleBatchOperate(){
          if(this.multipleSelection==null||this.multipleSelection.length<1){
            this.$message({
              message: '请选择要操作的条目',
              type: 'warning',
              duration: 1000
            });
            return;
          }
          if(this.operateType===1){
            let ids=[];
            for(let i=0;i<this.multipleSelection.length;i++){
              ids.push(this.multipleSelection[i].id);
            }
            this.deleteReason(ids);
          }
        },
        handleSizeChange(val){
          this.listQuery.pageNum = 1;
          this.listQuery.pageSize = val;
          this.getList();
        },
        handleCurrentChange(val){
          this.listQuery.pageNum = val;
          this.getList();
        },
        getList(){
          this.listLoading = true;
          const param = {
            "nickName": this.listQuery.nickName===""?null : this.listQuery.nickName,
            "modeUserCode": this.listQuery.userCode===""?null : this.listQuery.userCode,
            "hasChatterMode": this.listQuery.hasChatterMode===""||this.listQuery.hasChatterMode===null?null:this.listQuery.hasChatterMode,
            "chatterNickName":this.listQuery.chatterNickName===""?null : this.listQuery.chatterNickName,
            "chatterAccountId":this.listQuery.chatterUserCode===""?null : this.listQuery.chatterUserCode,
            "page": this.listQuery.pageNum,
            "pageSize": this.listQuery.pageSize
          };
          fetchModelList(param).then(response => {
            this.listLoading = false;
            this.list = response.data.data;
            this.total = response.data.total;
          });
        },
        deleteReason(ids){
          this.$confirm('是否要进行该删除操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let params = new URLSearchParams();
            params.append("ids",ids);
            deleteReason(params).then(response=>{
              this.$message({
                message: '删除成功！',
                type: 'success',
                duration: 1000
              });
              this.listQuery.pageNum=1;
              this.getList();
            });
          })
        },
      }
    }
  </script>
  <style scoped>
    .input-width {
      width: 80%;
    }
    .image{
    height:50px;
    width:50px;
    object-fit:contain
  }
  .operation_item{
    color: #409EFF; 
    border-bottom: 1px solid #409EFF;
    padding-bottom:2px;
  }
  </style>
